package com.liuwei.msmall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuwei.msmall.common.dto.SocialUserDTO;
import com.liuwei.msmall.common.utils.HttpUtils;
import com.liuwei.msmall.common.utils.PageUtils;
import com.liuwei.msmall.common.utils.Query;
import com.liuwei.msmall.member.dao.MemberDao;
import com.liuwei.msmall.member.entity.MemberEntity;
import com.liuwei.msmall.member.service.MemberLevelService;
import com.liuwei.msmall.member.service.MemberService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public MemberEntity login(SocialUserDTO to) throws Exception {

        String uid = to.getUid();

        //1.判断数据库中是否存在此用户
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));

        if (memberEntity != null) {
            //已经登录过
            //更新令牌和令牌生命周期
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(to.getAccess_token());
            entity.setExpiresIn(String.valueOf(to.getExpires_in()));
            this.updateById(entity);
            memberEntity.setExpiresIn(String.valueOf(to.getExpires_in()));
            memberEntity.setAccessToken(to.getAccess_token());

            return memberEntity;
        } else {
            //没有查到就重新注册

            MemberEntity registerMember = new MemberEntity();
//            try {
            //发送请求获取用户基本信息,根据传过来的uid和accessToken从微博中查出用户基本信息
            Map<String, String> queryMap = new HashMap<>();
            queryMap.put("uid", uid);
            queryMap.put("access_token", to.getAccess_token());
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), queryMap);
            //判断查询是否成功
            if (response.getStatusLine().getStatusCode() == 200) {
                JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
                //所在城市
                String location = (String) jsonObject.get("location");
                //昵称
                String name = (String) jsonObject.get("name");
                //签名
                String description = (String) jsonObject.get("description");
                //头像
                String avatar_hd = (String) jsonObject.get("avatar_hd");
                //邮箱
                String email = (String) jsonObject.get("email");
                //性别
                String gender = (String) jsonObject.get("gender");

                registerMember.setCity(location);
                registerMember.setEmail(email);
                registerMember.setNickname(name);
                registerMember.setHeader(avatar_hd);
                registerMember.setSign(description);
                registerMember.setGender("m".equals(gender) ? 1 : 0);
            }
//            } catch (Exception e) {}
            //注册时间
            registerMember.setCreateTime(new Date());
            registerMember.setAccessToken(to.getAccess_token());
            registerMember.setSocialUid(Long.parseLong(uid));
            registerMember.setExpiresIn(String.valueOf(to.getExpires_in()));
            //会员默认等级
            registerMember.setLevelId(memberLevelService.getDefaultLevel().getId());

            //注册用户
            this.save(registerMember);

            return registerMember;
        }

    }

}